package cn.itaccount.dao.impl;

import cn.itaccount.dao.accountDao;
import cn.itaccount.domain.Account;
import cn.ittest.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class accountDaoImpl implements accountDao {
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    @Override
    public Account findById(int id) {
        Account account = null;
        try {
            con = JDBCUtil.getConnection();
            String sql = "select * from account where id = ?";
            ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            rs = ps.executeQuery();
            while(rs.next()) {
                account = new Account();
                account.setId(rs.getInt(1));
                account.setName(rs.getString(2));
                account.setMoney(rs.getFloat(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(con,ps,rs);
        }
        return account;
    }

    @Override
    public void updateAccount(Connection con, Account account) {
        try{
            String sql="update account set money = ? where id = ?";
            ps=con.prepareStatement(sql);
            ps.setFloat(1,account.getMoney());
            ps.setInt(2,account.getId());
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
